package com.suwish.pc.ddms;

import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.Log;
import com.suwish.pc.Setting;
import com.suwish.pc.adb.AdbManager;

/**
 * 
 * @author Min
 *
 */
public class DdmsManager {

	private AndroidDebugBridge bridge = null;
	
	public DdmsManager(){
		AndroidDebugBridge.init(false);
	}
	/**
	 * 
	 * 启动DDMS并使用300 * 100毫秒时间等待设备就绪。
	 * 
	 * 
	 */
	public void startDdmsAndWaitTimeOut(){
		startDdmsManager();
		waitDeviceList();
	}
	/**
	 * 启动DDMS管理器，内部实现为创建{@link AndroidDebugBridge}
	 * 
	 */
	public void startDdmsManager(){
		Log.setLogOutput(new LogHandler());
		boolean isSocket = Setting.isTarget("adb.mode", "socket");
		bridge = isSocket ? AndroidDebugBridge.createBridge(/*AdbManager.ADB_PATH, true*/) :
		AndroidDebugBridge.createBridge(AdbManager.ADB_PATH, true);
		LogHandler.errorExit = false;
	}
	/**
	 * 停止DDMS，并停止{@link AndroidDebugBridge}实例
	 * 
	 * 
	 */
	public void stopDdmsManager(){
		if(bridge == null) return;
		AndroidDebugBridge.terminate();
		bridge = null;
	}
	
	public IDevice[] getDevices(){
		return bridge.getDevices();
	}
	
	public AndroidDebugBridge getBridge(){
		return bridge;
	}
	
	public void addDeviceChangeListener(IDeviceChangeListener l){
		AndroidDebugBridge.addDeviceChangeListener(l);
	}
	public void removeDeviceChangeListener(IDeviceChangeListener l){
		AndroidDebugBridge.removeDeviceChangeListener(l);
	}
//	public void test(){
//		AndroidDebugBridge bridge = AndroidDebugBridge.createBridge(/*AdbManager.ADB_PATH, true*/);
//		waitDeviceList(bridge);
////		bridge.addDeviceChangeListener(listener)
//		IDevice devices[] = bridge.getDevices();  
//		for(IDevice device : devices){
//			System.err.println(device.getSerialNumber());
//		}		
//		AndroidDebugBridge.addDeviceChangeListener(new IDeviceChangeListener() {
//			
//			@Override
//			public void deviceDisconnected(IDevice device) {
//				System.err.println("deviceDisconnected " + device);
//				
//			}
//			
//			@Override
//			public void deviceConnected(IDevice device) {
//				System.err.println("deviceConnected " + device);
//				
//			}
//			
//			@Override
//			public void deviceChanged(IDevice device, int changeMask) {
//				System.err.println("deviceChanged " + device);
//				
//			}
//		});
//	}
	private void waitDeviceList() {
		if(bridge == null) return;
		int count = 0;
		while (bridge.hasInitialDeviceList() == false) {
			try {
				Thread.sleep(100);
				count++;
			} catch (InterruptedException e) {
				// pass
			}
			// let's not wait > 10 sec.
			if (count > 300) {
				throw new RuntimeException("Timeout getting device list!");
			}
		}
	}

}
